﻿using System.IO;
using System.Reflection;
using System.Xml;
using EPiServer.Framework.Localization;

namespace ElencySolutions.MultipleProperty
{
    /// <summary>
    ///     Language helper class
    /// </summary>
    internal static class LanguageHelper
    {
        private static XmlDocument _document;
        private static readonly object Locker = new object();

        /// <summary>
        ///     Tries to get text from a language file based on the supplied xpath expression.  If the text
        ///     cannot be found a fallback value is retrieved from an embedded resource
        /// </summary>
        /// <param name="xpath">Xpath expression</param>
        /// <returns>Returns translated text</returns>
        public static string Translate(string xpath)
        {
            return LocalizationService.Current.GetString(xpath, GetFallbackText(xpath));
        }

        /// <summary>
        ///     Gets the fall back text from the embedded resource
        /// </summary>
        /// <param name="xpath">Xpath expression</param>
        /// <returns>fallback text if defined</returns>
        private static string GetFallbackText(string xpath)
        {
            if (_document == null)
            {
                lock (Locker)
                {
                    if (_document == null)
                    {
                        string xml;

                        using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("ElencySolutions.MultipleProperty.lang.lang.xml"))
                        {
                            using (var streamReader = new StreamReader(stream))
                            {
                                xml = streamReader.ReadToEnd();
                            }
                        }

                        _document = new XmlDocument();
                        _document.LoadXml(xml);
                    }
                }
            }

            if (!xpath.StartsWith("/"))
                xpath = string.Concat("/", xpath);

            return _document.SelectSingleNode("/languages/language" + xpath).InnerText.Trim();
        }
    }
}